<?php

namespace App\Services\Admin;

use App\Exceptions\LogicException;
use App\Models\Admins;
use App\Models\AdminRole;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class AdminsService
{
    protected $adminsModel;
    protected $adminRoleModel;
    protected $communityModel;

    public function __construct(Admins $adminsModel, AdminRole $adminRoleModel)
    {
        $this->adminsModel = $adminsModel;
        $this->adminRoleModel = $adminRoleModel;
    }

    /**
     * 获取管理员列表
     * @param array $params 查询参数
     * @return array
     */
    public function list(array $params): array
    {
        $fields = ['id', 'username', 'email', 'name', 'avatar', 'status', 'created_at'];
        $result = $this->adminsModel->list($params, $fields);
        foreach ($result['items'] as &$value) {
            $adminId = $value['id'];
            $adminRoles = $this->adminRoleModel->getAdminRoles($adminId);
            $roles = $adminRoles ? array_column($adminRoles, 'name') : [];
            $value['roles'] = $roles;
        }
        return $result;
    }

    /**
     * 获取管理员详情
     * @param int $id 管理员ID
     * @return array
     * @throws LogicException
     */
    public function view(int $id): array
    {
        $fields = ['id', 'username', 'email', 'name', 'avatar', 'status', 'community_ids'];
        $admin = $this->adminsModel->take(['id' => $id], $fields);
        if (empty($admin)) {
            throw new LogicException('管理员不存在');
        }

        // 获取管理员角色
        $roles = $this->adminRoleModel->search(['admin_id' => $id], ['role_id']);
        $adminRoles = [];
        foreach ($roles as $role) {
            $adminRoles[] = strval($role['role_id']);
        }
        $admin['roles'] = $adminRoles;

        return $admin;
    }

    /**
     * 创建管理员
     * @param array $data 管理员数据
     * @param int $userId 当前操作用户ID
     * @return array
     * @throws LogicException
     */
    public function create(array $data, int $userId = 0): array
    {
        if (!empty($data['email'])) {
            if ($this->adminsModel->take(['email' => $data['email']], ['id'])) {
                throw new LogicException('邮箱已存在');
            }
        }
        if ($this->adminsModel->take(['username' => $data['username']], ['id'])) {
            throw new LogicException('用户名已存在');
        }
        $data['password'] = Hash::make($data['password']);
        $data['status'] = $data['status'] ?? Admins::STATUS_ENABLED;
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;

        // 开启事务
        DB::beginTransaction();
        try {
            // 创建管理员
            $id = $this->adminsModel->create($data);

            // 如果有角色数据，创建管理员角色关联
            if (!empty($data['roles']) && is_array($data['roles'])) {
                foreach ($data['roles'] as $roleId) {
                    $this->adminRoleModel->create([
                        'admin_id' => $id,
                        'role_id' => $roleId
                    ]);
                }
            }

            DB::commit();
            return ['id' => $id];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new LogicException($e->getMessage());
        }
    }

    /**
     * 更新管理员
     * @param int $id 管理员ID
     * @param array $data 更新数据
     * @param int $userId 当前操作用户ID
     * @return array
     * @throws LogicException
     */
    public function update(int $id, array $data, int $userId = 0): array
    {
        if (!$this->adminsModel->take(['id' => $id], ['id'])) {
            throw new LogicException('管理员不存在');
        }
        if (isset($data['username'])) {
            $existingUser = $this->adminsModel->take(['username' => $data['username']], ['id']);
            if ($existingUser && $existingUser['id'] != $id) {
                throw new LogicException('用户名已存在');
            }
        }
        if (!empty($data['email'])) {
            $existingUser = $this->adminsModel->take(['email' => $data['email']], ['id']);
            if ($existingUser && $existingUser['id'] != $id) {
                throw new LogicException('邮箱已存在');
            }
        }
        if (isset($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        }

        // 编辑关联角色
        if (isset($data['roles']) && is_array($data['roles'])) {
            // 查询现有角色
            $existingRoles = $this->adminRoleModel->search(['admin_id' => $id], ['role_id']);
            $existingRoleIds = array_column($existingRoles, 'role_id');

            // 需要添加的角色
            $rolesToAdd = array_diff($data['roles'], $existingRoleIds);
            foreach ($rolesToAdd as $roleId) {
                $addData = [
                    'admin_id' => $id,
                    'role_id' => $roleId
                ];
                $this->adminRoleModel->create($addData);
            }

            // 需要删除的角色
            $rolesToDelete = array_diff($existingRoleIds, $data['roles']);
            if (!empty($rolesToDelete)) {
                $deleteParams = [
                    'admin_id' => $id,
                    'role_ids' => $rolesToDelete
                ];
                $this->adminRoleModel->clear($deleteParams);
            }
        }

        $rows = $this->adminsModel->modify($id, $data);
        return ['affected_rows' => $rows];
    }

    /**
     * 删除管理员
     * @param int $id 管理员ID
     * @return array
     * @throws LogicException
     */
    public function delete(int $id): array
    {
        if (!$this->adminsModel->take(['id' => $id], ['id'])) {
            throw new LogicException('管理员不存在');
        }
        $rows = $this->adminsModel->remove($id);
        return ['affected_rows' => $rows];
    }
}
